import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CategoryEntity } from '@/entity/category.entity';
import { Repository } from 'typeorm';
import { CreateCategoryDto } from '@/modules/category/dto/create-category.dto';
import { UpdateCategoryDto } from '@/modules/category/dto/update-category.dto';
import { RestaurantEntity } from '@/entity/restaurant.entity';

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(CategoryEntity)
    private readonly categoryRepository: Repository<CategoryEntity>,
    @InjectRepository(RestaurantEntity)
    private readonly restaurantRepository: Repository<RestaurantEntity>,
  ) {}

  async findAll(
    page = 1,
    limit = 10,
  ): Promise<{ list: CategoryEntity[]; total: number }> {
    const [data, total] = await this.categoryRepository.findAndCount({
      skip: (page - 1) * limit,
      take: limit,
    });
    return {
      list: data,
      total,
    };
  }

  async findOne(id: number): Promise<CategoryEntity> {
    const result = await this.categoryRepository.findOne({ where: { id } });
    if (!result) {
      throw new NotFoundException('指定的菜品类别不存在');
    }
    return result;
  }

  async create(createCategoryDto: CreateCategoryDto): Promise<CategoryEntity> {
    const { restaurantId } = createCategoryDto;
    // 查询餐厅是否存在
    const restaurant = await this.restaurantRepository.query(
      `SELECT * FROM restaurant_entity WHERE id = ${restaurantId}`,
    );
    if (!restaurant || restaurant.length === 0) {
      throw new NotFoundException('指定的餐厅不存在');
    }
    const category = this.categoryRepository.create(createCategoryDto);
    return this.categoryRepository.save(category);
  }

  async update(
    id: number,
    updateCategoryDto: UpdateCategoryDto,
  ): Promise<CategoryEntity> {
    await this.categoryRepository.update(id, updateCategoryDto);
    return this.categoryRepository.findOne({ where: { id } });
  }

  async delete(id: number) {
    const category = await this.categoryRepository.findOne({ where: { id } });
    if (!category) {
      throw new NotFoundException('指定的菜品类别不存在');
    }
    await this.categoryRepository.delete(id);
    return `${category.name}已删除`;
  }

  async findByRestaurantId(
    restaurantId: number,
    page: number,
    limit: number,
  ): Promise<{ list: CategoryEntity[]; total: number }> {
    const isRestaurantExist = await this.restaurantRepository.query(
      `SELECT * FROM restaurant_entity WHERE id = ${restaurantId}`,
    );
    if (!isRestaurantExist || isRestaurantExist.length === 0) {
      throw new NotFoundException('指定的餐厅不存在');
    }
    const [list, total] = await this.categoryRepository.findAndCount({
      where: { restaurantId },
      skip: (page - 1) * limit,
      take: limit,
    });
    return { list, total };
  }
}
